<template>
    <div>
        <!-- 新增/修改勋章 -->
        <el-dialog :fullscreen="fullscreen" :visible.sync="isShow" width="700px" top="3%" :show-close="false" :before-close="beforeClose">
            <el-row slot="title">
                <el-col :span="10" style="padding-top: 5px">
                    <span>{{medalrankDecide == 'add' ? '新增勋章': '编辑勋章'}}</span>
                </el-col>
                <el-col :span="2" :offset="11">
                    <el-button type="text" v-if="!fullscreen" icon="iconfont ali-quanping" @click="fullscreen = true" style="float: right"></el-button>
                    <el-button type="text" v-else icon="iconfont ali-zuixiaohua" @click="fullscreen = false" style="float: right"></el-button>
                </el-col>
                <el-col :span="1">
                    <el-button type="text" icon="iconfont ali-guanbi" @click="parentCloseEvent" style="float: right"></el-button>
                </el-col>
            </el-row>
            <el-form ref="medalRankForm" :model="form" :inline="true" label-width="90px" v-loading="loading" element-loading-text="加载中...">
                <!-- 头 -->
                <section class="container-box">
                    <el-form-item label="勋章名称" prop="medalrank_name" :rules="filter_rules({required:true})">
                        <el-input clearable v-model.trim="form.medalrank_name" maxlength="30" placeholder="请输入勋章名称"></el-input>
                    </el-form-item>
                    <el-form-item label="分组名称" prop="medal_id" :rules="filter_rules({required:true})">
                        <el-select clearable style="width:100%" v-model="form.medal_id" placeholder="请选择">
                            <el-option v-for="item in groupList" :key="item.id" :label="item.label" :value="item.id"> </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="等级" prop="rank" :rules="filter_rules({required:true})">
                        <el-select clearable style="width:100%" v-model="form.rank" placeholder="请选择">
                            <el-option v-for="item in rankList" :key="item.id" :label="item.label" :value="item.id"> </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="积分类别" prop="integraltype_id" :rules="filter_rules({required:true})">
                        <el-select clearable style="width:100%" v-model="form.integraltype_id" placeholder="请选择">
                            <el-option v-for="item in classList" :key="item.id" :label="item.label" :value="item.id"> </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="积分奖励" prop="reward_integral">
                        <el-input clearable v-model.number="form.reward_integral" placeholder="请输入积分奖励"></el-input>
                    </el-form-item>
                    <el-form-item label="获奖规则" prop="medalrank_rule" :rules="filter_rules({required:true})">
                        <textarea cols="70" rows="5" style="padding: 10px; border-radius: 5px;" maxlength="500" placeholder="请输入详细描述..." v-model.trim="form.medalrank_rule"></textarea>
                    </el-form-item>
                </section>
                <!-- 获得条件 -->
                <section class="container-box">
                    <el-form-item label="获得条件">
                    </el-form-item>
                    <br>
                    <div class="list-box" v-for="(condition,i) in conditions" :key="condition.num">
                        <div v-if="i != 0">
                            <i class="iconfont ali-cc-close-square" @click="delRow(i)"></i>
                        </div>
                        <br>
                        <!-- 模板 -->
                        <conditionTemp ref="conditionChild"></conditionTemp>
                    </div>
                </section>
                <div class="list-button" @click="addCondition">
                    <span>继续添加</span>
                    <i class="iconfont ali-addnewlist"></i>
                </div>
                <!-- 图片 -->
                <section class="container-box">
                    <el-form-item label="图片">
                    </el-form-item>
                    <br>
                    <el-form-item label="未获得图片" label-width="110px" prop="loss_img" :rules="filter_rules({type: 'upload'})">
                        <el-upload action="/api/backstage/fileUpload" class="avatar-uploader" name="file_path" :before-upload="beforeAvatarUpload" :on-success='handleLossSuccess' :show-file-list="false">
                            <img v-if="form.loss_img" :src="form.loss_img" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="已获得图片" label-width="110px" prop="have_img" :rules="filter_rules({type: 'upload'})">
                        <el-upload action="/api/backstage/fileUpload" class="avatar-uploader" name="file_path" :before-upload="beforeAvatarUpload" :on-success='handleHaveSuccess' :show-file-list="false">
                            <img v-if="form.have_img" :src="form.have_img" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </el-form-item>
                    <br>
                    <span style="margin-left: 30px;color: #F56C6C;">建议上传600px*600px的png图片</span>
                </section>
            </el-form>
            <!-- submit -->
            <section class="submit">
                <el-button type="primary" style="width: 100px;" @click="validate('medalRankForm')">保存</el-button>
            </section>
        </el-dialog>
    </div>
</template>
<script>
import { mapGetters } from 'vuex'
import { medal_listAll } from '@/api/medal'
import config from '@/utils/conf'
import conditionTemp from './conditionTemp'
import { medalrank_save, medalrank_edit, medalrank_findById } from '@/api/medalrank'
import { integraltype_listAll } from '@/api/integraltype'

export default {
    name: 'createMe',
    components: { conditionTemp },
    props: {
        isShow: Boolean
    },
    computed: {
        ...mapGetters([
            'medalrankDecide',
        ]),
        rankList() {
            return this.conf.rank.map((item, i) => {
                return { id: i + 1, label: item }
            })
        }
    },
    data() {
        return {
            groupList: [],
            conf: config,
            fullscreen: false,
            form: { medalrankConditions: null, loss_img: '', have_img: '' },
            conditions: [{ num: 1 }],
            ossPublicUrl: localStorage.getItem("ossPublicUrl"),
            loading: false,
            classList: [] //积分类别
        }
    },
    methods: {
        async editObj() {
            this.$emit('closeTemp');
            const parms = {...this.form, company_id: localStorage.getItem('companyId') - 0}
            const { data } = await medalrank_edit(parms);
            if (data.status == 100) {
                this.$message.success("编辑成功");
                this.$emit("initParentList")
            }
        },
        async saveObj() {
            this.$emit('closeTemp');
            const parms = {...this.form, company_id: localStorage.getItem('companyId') - 0}
            const { data } = await medalrank_save(parms);
            if (data.status == 100) {
                this.$message.success("操作成功");
                this.$emit("initParentList")
            }
        },
        async getConditions() {
            let result = [];
            for (let i = 0; i < this.conditions.length; i++) {
                let ele = this.conditions[i];
                let child = this.$refs.conditionChild[i];
                child.validate()//表单校验
                if (child.decide) {//判断是否可以获取数据
                    //获取表单数据 并 合并
                    const childForm = {...child.form, is_continuity: child.form.is_continuity ? 1 : 0}
                    result[i] = {...this.conditions[i], ...childForm};
                } else {
                    return false
                }
            }
            this.form.medalrankConditions = JSON.stringify(result)
            return true;
        },
        async validate(e) {
            let decide = await this.getConditions();
            if (!decide) {
                return;
            }
            this.$refs[e].validate((valid) => {
                if (valid) {
                    this.medalrankDecide == 'add' ? this.saveObj() : this.editObj()
                } else {
                    return false;
                }
            });
        },
        beforeAvatarUpload(file) {
            let name = file.name.split('.');
            if (name[name.length - 1] === 'jpg' || name[name.length - 1] === 'jpeg' || name[name.length - 1] === 'png') {
                return file
            } else {
                this.$message.error('图片只能是 jpeg/png 格式!')
                return false
            }
        },
        handleLossSuccess(res, file, fileList) {
            if (res.status == 100) {
                this.form.loss_img = this.ossPublicUrl + '/' + res.data.file_path
            }
        },
        handleHaveSuccess(res, file, fileList) {
            if (res.status == 100) {
                this.form.have_img = this.ossPublicUrl + '/' + res.data.file_path
            }
        },
        beforeClose(e) {
            this.$emit('closeTemp');
        },
        parentCloseEvent() {
            this.$emit('closeTemp');
        },
        delRow(i) {
            this.conditions.splice(i, 1);
        },
        addCondition() {//继续添加
            this.conditions.push({ num: this.conditions.length + 1 })
        },
        async initGroupList() {
            let { data } = await medal_listAll({ company_id: localStorage.getItem('companyId') });
            if (data.status == 100) {
                this.groupList = data.data.rows.map(item => {
                    return { id: item.id, label: item.medal_name }
                })
            }
        },
        async initClassList(){
            let { data } = await integraltype_listAll({ company_id: localStorage.getItem('companyId') });
            if (data.status == 100) {
                this.classList = data.data.rows.map(item => {
                    return { id: item.id, label: item.integraltype_name }
                })
            }
        },
        async clearForm() {
            this.form = { medalrankConditions: null, loss_img: '', have_img: '' }
            this.conditions = [{ num: 1 }]
            await this.$nextTick();
            this.$refs.conditionChild[0].clearForm()
        },
        async editForm(e) {
            this.loading = true;
            this.conditions = []
            this.form = { medalrankConditions: null, loss_img: '', have_img: '' }
            let { data } = await medalrank_findById({ id: e.id });
            if (data.status == 100) {
                let result = data.data;
                this.form = result;
                this.conditions = result.medalrankConditions;
                await this.$nextTick();
                for (var i = 0; i < result.medalrankConditions.length; i++) {
                    var ele = result.medalrankConditions[i];
                    await this.$refs.conditionChild[i].editForm(ele);
                }
            }
            this.loading = false;
        }
    },
    created() {
        this.initGroupList();
        this.initClassList();
    }
}
</script>
<style lang="scss" scoped>
.container-box {
    background-color: #FAFAFA;
    padding-top: 15px;
    margin-bottom: 10px;
}

.list-box {
    border-bottom: 1px solid #E4E7ED;
    padding-top: 10px;
    .ali-cc-close-square {
        color: #F56C6C;
        margin-left: 10px;
        font-size: 20px;
        &:hover {
            cursor: pointer;
        }
    }
}

.list-button {
    padding-bottom: 10px;
    text-align: center;
    .ali-addnewlist {
        font-size: 25px;
    }
    &:hover {
        cursor: pointer;
    }
}

.submit {
    text-align: center;
    margin: 40px 0 0 0;
}

$border: 1px dashed #d9d9d9;
$picture-size: 120px;
.avatar-uploader {
    .el-upload {
        border: $border;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        &:hover {
            border-color: #409EFF;
        }
    }
}

.avatar-uploader-icon {
    border: $border;
    font-size: 28px;
    color: #8c939d;
    width: $picture-size;
    height: $picture-size;
    line-height: $picture-size;
    text-align: center;
    border-radius: 5px;
}

.avatar {
    width: $picture-size;
    height: $picture-size;
    display: block;
    border-radius: 5px;
}
</style>
